<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use think\Loader;
use think\Db;
use think\Config;
// 导出 Excel 
/*
# table 数据库表名   str
# headArr Excel 表头 arr
# filename 表名 前缀 str
# fields  数据库字段  str
*/
function listToExcel($table , $fields,$headArr,$filename='filename'){
    loader::import('PHPExcel.PHPExcel', EXTEND_PATH);
    loader::import('PHPExcel.PHPExcel.Writer.Excel5', EXTEND_PATH);
    loader::import('PHPExcel.PHPExcel.IOFactory', EXTEND_PATH);
  
    $objPHPExcel = new PHPExcel;

    $fileName = $filename . date('Y_m_d_H_i_s') . '.xls';
    $list = Db::table($table)->field($fields)->select();

// return $list;

    $key = ord('A');
    for ($i = 0; $i < count($headArr); $i++) {
        $colnum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colnum . '1', $headArr[$i]);
        $key++;
    }

    if ($list) {
        $mark = 2; //从第二行开始 
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($list as $key => $val) {
            $span = ord('A');
            foreach ($val as $k => $v) {
                $j = chr($span);
                $objActSheet->setCellValue($j . $mark, $v);
                $span++;
            }
            $mark++;
        }
    }

    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
}


// 接口返回 json字符串
function to_json_encode($code = 400, $msg = null, $data = null){
    //dump(\think\Request::instance()->ip());
    if('192.168.1.153' == \think\Request::instance()->ip())
    {
        echo json_encode(array('code' => $code, 'msg' => $msg, 'data' => $data));

    }else{
        die(json_encode(array('code' => $code, 'msg' => $msg, 'data' => $data)));
    }
    //die(json_encode(array('code' => $code, 'msg' => $msg, 'data' => $data)));
}


//动态 加载 指定作用范围 配置文件
function  load_scope_config($file,$scope='',$path=CONF_PATH,$ext=CONF_EXT)
{
    if($scope=='')
    {
        $scope = $file;
    }
    $path_filename = $path.$file.$ext;

    return Config::load($path_filename,'',$scope);
}
//发送手机验证码  登录、 注册、 修改密码
/**
*   $option=['code'=>2354,'template'=>'register'];
*/
function send_sms_verify_code($phone,$option){

    Loader::import('AliyunSms.SignatureHelper');

    $params = array();

    // *** 需用户填写部分 ***
    $aliyun_config = load_scope_config('aliyun');
    
    // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
    $accessKeyId = $aliyun_config['access_key_id'];
    $accessKeySecret =$aliyun_config['access_key_secret'];

    // fixme 必填: 短信接收号码
    $params["PhoneNumbers"] = $phone;

    // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
    $params["SignName"] = $aliyun_config['sms']['sign_name'];

    // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
    $params["TemplateCode"] = $aliyun_config['sms']['templates'][$option['template']];

    // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
    $params['TemplateParam'] = array(
        "code" => $option['code'],
    );
    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }

    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
    $helper = new \Aliyun\DySDKLite\SignatureHelper();

    $content = $helper->request(
                $accessKeyId,
                $accessKeySecret,
                "dysmsapi.aliyuncs.com",
                array_merge($params, array(
                    "RegionId" => "cn-hangzhou",
                    "Action" => "SendSms",
                    "Version" => "2017-05-25",
                ))
                // fixme 选填: 启用https
                // ,true
            );

       return $content;
   

}

function check_valid_phone($phone)
{
    return is_numeric($phone) && strlen($phone) ==11;
}
function encrypt_password($password)
{
    $key='zjhzzdhcn';
   
    return md5(sha1(crypt($password,$key)));
}
function handle_upload_image(\think\File $file,$path)
{
    $info = $file->move(UPLOAD_ROOT_PATH . $path);

    $save_name = $info->getSaveName();

    $save_name = str_replace('\\', '/', $save_name);

    return  $save_name;

}
function get_image_url($sub_path,$image_name,$with_host=true)
{
     $uri = UPLOAD_ROOT_PATH.$sub_path.'/'.$image_name;
     return $with_host?HOST_URL.'/'.$uri:$uri;
}
function get_image_save_path($image_url)
{
    return substr($image_url,strlen(HOST_URL.'/'.UPLOAD_ROOT_PATH));
}
function get_today_timestamp()
{
    $date_info =getdate();
    return mktime(0,0,0,$date_info['mon'],$date_info['mday'],$date_info['year']);

}

//过滤 字符串中表情字符
 function filter_emoji($str)
{
    $str = preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);

    return $str;
}

